﻿using System;
using System.Collections.Generic;
using System.Linq;
using Shop.Base.Entity;
using Shop.Base.Entity.Delete;
using Shop.Base.Entity.Insert;
using Shop.Base.Entity.Update;
using Shop.Base.Interface;
using Shop.Entity;
using Shop.Server;
using SqlSugar;

namespace Shop.Base.Server
{
    public class SystemMenuButton : BaseServer<SystemMenuButtonPo>, ISystemMenuButton
    {
        public bool Delete(List<DeleteSystemMenuButton> t)
        {
           return db.Deleteable(t).ExecuteCommand()>0;
        }

        public SystemMenuButtonPo Find(Guid id)
        {
            return db.Queryable<SystemMenuButtonPo>().Where(x => x.Id == id).First();
        }

        public List<SystemMenuButtonPo> GetAll(Guid menuId)
        {
            return db.Queryable<SystemMenuButtonPo>().Where(x=>x.MenuId==menuId).ToList();
        }

        public List<SystemMenuButtonPo> GetAll()
        {
            return db.Queryable<SystemMenuButtonPo>().ToList();
        }

        public bool MultSave(List<AddSystemMenuButton> t)
        {
            if (!t.Any()) return false;
            try
            {
                var allMenu = GetAll(t[0].MenuId);
                db.Ado.BeginTran();
                t.ForEach(x =>
                {
                    if (allMenu.Exists(c => c.ButtonId == x.ButtonId && c.MenuId == x.MenuId))
                    {
                        var mo = allMenu.Find(c => c.ButtonId == x.ButtonId && c.MenuId == x.MenuId);
                        x.Id = mo.Id;
                        db.Updateable(x).ExecuteCommand();
                    }
                    else
                    {
                        db.Insertable(x).ExecuteCommand();
                    }
                });
                allMenu.ForEach(x =>
                {
                    if (!t.Exists(c => c.ButtonId == x.ButtonId && c.MenuId == x.MenuId))
                    {
                        db.Deleteable<SystemMenuButtonPo>(x.Id).ExecuteCommand();
                    }
                });
                db.Ado.CommitTran();
                return true;
            }
            catch (Exception e)
            {
                db.Ado.RollbackTran();
                return false;
            }
        }

        public bool Insert(AddSystemMenuButton t)
        {
            return db.Insertable(t).ExecuteCommand() > 0;
        }

        public bool Update(UpdateSystemMenuButton t)
        { 
            return db.Updateable(t).ExecuteCommand() > 0;
        }
    }
}